/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kizitonwose.calendarview.fraction;

import com.kizitonwose.calendarview.CalendarView;
import com.kizitonwose.calendarview.ResourceTable;
import com.kizitonwose.calendarview.model.CalendarDay;
import com.kizitonwose.calendarview.model.CalendarMonth;
import com.kizitonwose.calendarview.model.enums.DayOwner;
import com.kizitonwose.calendarview.ui.ViewContainer;
import com.kizitonwose.calendarview.uinterface.DayBinder;
import com.kizitonwose.calendarview.uinterface.MonthHeaderFooterBinder;
import com.kizitonwose.calendarview.utils.DayExtensions;
import com.kizitonwose.calendarview.utils.StringUtils;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * @version 1.0
 * @date 2021/2/24 10:42
 */
public class Example2Fraction extends BaseFraction {
    private CalendarView exTwoCalendar;
    private Image imageCheck;
    private Image imageBack;
    private LocalDate selectedDate;
    private LocalDate today = LocalDate.now();
    private DateTimeFormatter monthTitleFormatter = DateTimeFormatter.ofPattern("MMMM");
    private ComponentContainer legendLayout;
    private Text title;
    private ShapeElement textDayNoBgElement = new ShapeElement();

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_example_2_fraction;
    }

    @Override
    protected void initComponent(Component content, ComponentContainer container, Intent intent) {
        textDayNoBgElement.setAlpha(0);
        exTwoCalendar = findComponentById(ResourceTable.Id_exOneCalendar);
        title = findComponentById(ResourceTable.Id_title);
        title.setText(ResourceTable.String_example_2_title);
        legendLayout = findComponentById(ResourceTable.Id_legendLayout);
        imageCheck = findComponentById(ResourceTable.Id_menuItemDone);
        imageBack = findComponentById(ResourceTable.Id_image_back);
        imageCheck.setClickedListener(component -> {
            closePage();
        });
        imageBack.setClickedListener(component -> {
            backFraction();
        });
        ShapeElement shapeElement = new ShapeElement(mContext, ResourceTable.Graphic_example_2_blue_bg);
        legendLayout.setBackground(shapeElement);
        DayOfWeek[] daysOfWeek =  DayExtensions.daysOfWeekFromLocale();
        int childCount = legendLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            Text text = (Text) legendLayout.getComponentAt(i);
            text.setText(String.valueOf(daysOfWeek[i].name().charAt(0)));
            try {
                text.setTextColor(new Color(mContext.getResourceManager().getElement(ResourceTable.Color_example_2_white).getColor()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        exTwoCalendar.setup(YearMonth.now(), YearMonth.now().plusMonths(10), daysOfWeek[0]);
        exTwoCalendar.setDayBinder(new DayBinder<DayViewContainer>() {

            @Override
            public DayViewContainer create(Component component) {
                return new DayViewContainer(component);
            }

            @Override
            public void bind(DayViewContainer container, CalendarDay day) {
                try {
                    container.day = day;
                    Text textView = container.textView;
                    textView.setText(String.valueOf(day.getDate().getDayOfMonth()));
                    if (day.getOwner() == DayOwner.THIS_MONTH) {
                        textView.setVisibility(Component.VISIBLE);
                        if (selectedDate != null && day.getDate().isEqual(selectedDate)) {
                            textView.setTextColor(new Color(mContext.getResourceManager().getElement(ResourceTable.Color_example_2_white).getColor()));
                            ShapeElement element = new ShapeElement(mContext, ResourceTable.Graphic_example_2_selected_bg);
                            textView.setBackground(element);
                        } else if (day.getDate().isEqual(today)) {
                            textView.setTextColor(new Color(mContext.getResourceManager().getElement(ResourceTable.Color_example_2_red).getColor()));
                            textView.setBackground(textDayNoBgElement);
                        } else {
                            textView.setTextColor(new Color(mContext.getResourceManager().getElement(ResourceTable.Color_example_2_black).getColor()));
                            textView.setBackground(textDayNoBgElement);
                        }
                    } else {
                        textView.setVisibility(Component.INVISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        exTwoCalendar.setMonthHeaderBinder(new MonthHeaderFooterBinder<MonthViewContainer>() {
            @Override
            public MonthViewContainer create(Component component) {
                return new MonthViewContainer(component);
            }

            @Override
            public void bind(MonthViewContainer container, CalendarMonth month) {
                container.textView.setText(StringUtils.getFirstUpper(month.getYearMonth().getMonth().name().toLowerCase()) + " " + month.getYearMonth().getYear());
            }
        });
    }

    private void closePage() {
        if (selectedDate != null) {
            String text = "Selected: " + DateTimeFormatter.ofPattern("d MMMM yyyy").format(selectedDate);
            toast(text);
            backFraction();
        }
    }

    private void toast(String text){
        ToastDialog toastDialog = new ToastDialog(mContext.getApplicationContext());
        Component dialogComponent = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_example_2_toast, null, false);
        Text dialogText = (Text) dialogComponent.findComponentById(ResourceTable.Id_txToast);
        dialogText.setText(text);
        toastDialog.setComponent(dialogComponent);
        DisplayAttributes attributes = DisplayManager.getInstance().getDefaultDisplay(mContext).get().getAttributes();
        toastDialog.setSize((int) (attributes.width * 0.9), (int) (attributes.height * 0.07));
        toastDialog.show();
    }



    class DayViewContainer extends ViewContainer {
        CalendarDay day;
        Text textView;

        public DayViewContainer(Component component) {
            super(component);
            textView = (Text) component;
            component.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (day.getOwner() == DayOwner.THIS_MONTH) {
                        if (selectedDate != null && day.getDate().isEqual(selectedDate)) {
                            selectedDate = null;
                            exTwoCalendar.notifyDayChanged(day);
                        } else {
                            LocalDate oldDate = selectedDate;
                            selectedDate = day.getDate();
                            exTwoCalendar.notifyDateChanged(day.getDate());
                            if (oldDate != null) {
                                exTwoCalendar.notifyDateChanged(oldDate);
                            }
                        }
                        imageCheck.setVisibility(selectedDate == null? Component.INVISIBLE : Component.VISIBLE);
                    }
                }

            });

        }
    }

    class MonthViewContainer extends ViewContainer {
        Text textView;

        public MonthViewContainer(Component component) {
            super(component);
            textView = (Text) component.findComponentById(ResourceTable.Id_exTwoHeaderText);
        }
    }
}
